import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

/**
 * @author zhu
 * @date 2024-04-09
 */
public class DbUtilRunner {
    /**
     * 连接对象
     */
    private Connection connection;

    public DbUtilRunner(Connection connection) {
        this.connection = connection;
    }

    public int update(String sql, Object... params){
        PreparedStatement ps = null;
        try {
            ps = connection.prepareStatement(sql);
            setParamter(params, ps);
            return ps.executeUpdate();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }finally {
            DbUtil.close(null,ps,connection);
        }
    }

    private static void setParamter(Object[] params, PreparedStatement ps) throws SQLException {
        for (int i = 0; i < params.length; i++) {
            ps.setObject(i + 1, params[i]);
        }
    }

    public <T> List<T> queryList(Class<T> entity, String sql, Object... params){

        PreparedStatement ps = null;
        ResultSet rs = null;

        try {
            ps = connection.prepareStatement(sql);
            setParamter(params,ps);
            rs = ps.executeQuery();

            return beanListHandler(entity, rs);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    private <T> List<T> beanListHandler(Class<T> entity, ResultSet rs){

        List<T> list = new ArrayList<T>();

        try {
            T clazz = entity.getConstructor().newInstance();

            ResultSetMetaData rsmd = rs.getMetaData();
            int count = rsmd.getColumnCount();
            while (rs.next()) {
                for (int i = 0; i < count; i++) {
                    String columnLabel = rsmd.getColumnLabel(i + 1);

                    String fieldName = getFieldName(columnLabel,entity);
                    Object columnValue = rs.getObject(i + 1);

                    Field field = entity.getDeclaredField(fieldName);
                    field.setAccessible(true);

                    field.set(clazz,columnValue);
                }
                list.add(clazz);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return list;
    }

    private <T> String getFieldName(String columnLabel, Class<T> entity) {
        Field[] fields = entity.getDeclaredFields();

        for (Field field : fields) {
            if (field.isAnnotationPresent(Column.class)){
                String value =  field.getAnnotation(Column.class).value();

                if (value != null && value.equals(columnLabel)){
                    return field.getName();
                }
            }
        }
        return columnLabel;
    }
}
